package com.xjf.bookshelf;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.widget.AppCompatImageView;

/**
 * Create by XieJunFeng on 2019/12/11.
 */
public class BookImageView extends AppCompatImageView {
    private Book book;

    public BookImageView(Context context) {
        super(context);
    }

    public BookImageView(final Context context, AttributeSet attrs) {
        super(context, attrs);
        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (book!=null){
                    Toast.makeText(context,book.getName(),Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public BookImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    public Book getBook() {
        return book;
    }

    public void setBook(Book b) {
        this.book = b;
        setImageResource(book.getImg());
    }


    @Override
    public void setImageResource(int resId) {
        super.setImageResource(resId);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        return super.dispatchTouchEvent(event);
    }


    /**
     * 设置书本的高度和宽度比例固定
     *
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = width * 4 / 3;
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    }

}
